/*
 * @Description: 
 * @Author: Crism
 * @Github: https://gitee.com/crism/
 * @Date: 2019-01-25 15:31:17
 * @LastEditors: Crism
 * @LastEditTime: 2019-01-28 19:33:07
 */


const HttpUtil = require('../utils/HttpUtil')
const CommomUtil = require('../utils/CommomUtil')
const cheerio = require('cheerio')
const db_movie = require('../config').db_movie
const play_url = 'http://sj.dv.loltp.com.love6300.com/?m=vod-play-id-'
const search_url = 'http://sj.dv.loltp.com.love6300.com/index.php?m=vod-search-wd-'
const next_url = 'http://sj.dv.loltp.com.love6300.com/index.php?m=vod-search-pg-'
const movie_detail = 'http://sj.dv.loltp.com.love6300.com/?m=vod-detail-id-'
const domain = 'http://sj.dv.loltp.com.love6300.com'

module.exports.search_movie = search_movie
async function search_movie(movie_name, page_num) {
    let url = ''
    if(page_num> 1){
        url = next_url + page_num + '-wd-' + encodeURIComponent(movie_name)
    } else{
        url = search_url + encodeURIComponent(movie_name)
    }
    let html = await HttpUtil.httpGet(url)
    if (html) {
        let $ = cheerio.load(html, { decodeEntities: false })
        let list_content = $('ul.bd')
        let total_str = $('div.mt30').text().replace('条','')
        let total = total_str.substring(total_str.indexOf('的结果共')+4,total_str.length).trim()
        let page = Math.ceil(total/8)
        let movie = []
        list_content.find('li').each(function (index, item) {
            let obj = $(this)
            let poster = obj.find('img').attr('data-original')
            if(poster.substring(0,7) == '/tu.php'){
                poster = domain+poster
            }
            let movie_id = obj.find('p.name').find('a').attr('href').replace(/[^0-9]/ig,'')
            let actor = obj.find('p.name').next().text().replace("主演：","")
            movie.push({
                'title': obj.find('p.name').text(),
                'id': movie_id,
                'cover': poster,
                'actor': actor.length < 1 ? '佚名' : actor,
                'date': obj.find('p.name').next().next().find('a').text(),
                'detail': obj.find('p.fr').text(),
                'url': obj.find('a').attr('href')
            })
        })
        return [movie,total,page]
    }
    return [null,null,null]
}

async function get_rating(movie_id) {
    let httpData = JSON.parse(await HttpUtil.httpGet('http://sj.dv.loltp.com.love6300.com/inc/ajax.php?ac=score&tab=vod&id=' + movie_id))
    return httpData
}

module.exports.crawl_movie = crawl_movie
async function crawl_movie(movie_id) {
    let html = await HttpUtil.httpGet(movie_detail + movie_id)
    if (html) {
        let $ = cheerio.load(html, { decodeEntities: false })
        let movie_title = $('div.detail_wrap').find('h1.fl').text()
        let movie_ova = 0
        let movie_status = $('div.detail_wrap').find('span.fr').text() == '完结' ? true : false
        let list_content  = $('div.big_shadow_main')
        list_content.find('div.mlist').each(function (index, item) {
            let obj = $(this)
            movie_ova = movie_ova > obj.find('a').length ? movie_ova : obj.find('a').length
        })

        let movie_year = $('div.detail_wrap').find('p').eq(3).text()
        let movie_cover = $('div.img_wrap').find('img').attr('data-original')
        
        if(!CommomUtil.isEmpty(movie_cover) && movie_cover.substring(0,7) == '/tu.php'){
            movie_cover = domain + movie_cover
        }
        let httpData = await get_rating(movie_id)
        let movie = {
            'id': movie_id,
            'title': movie_title,
            'year': movie_year.substring(0,movie_year.indexOf('更')-1),
            'ova': movie_ova,
            'score': httpData.score,
            'scorenum': httpData.scorenum,
            'status': movie_status,
            'director': $('div.detail_wrap').find('p').eq(0).text().trimRight(),
            'actor': $('div.detail_wrap').find('p').eq(4).text().trimRight(),
            'images': movie_cover,
            'location': $('div.detail_wrap').find('p').eq(1).text().trimRight(),
            'language': $('div.detail_wrap').find('p').eq(2).text(),
            'detail': $('div.detail_wrap').find('p.content').text()
        }
        renew_hot_play_list(movie)
        return movie
    }
    return null
}

module.exports.crawl_play_url = crawl_play_url
async function crawl_play_url(movie_id) {
    let url =  play_url + movie_id + '-src-1-num-1.html'
    let html = await HttpUtil.httpGet(url)
    if (html) {
        let $ = cheerio.load(html, { decodeEntities: false })
        let content = $('div.play_wrap').find('script').html()
        content = content.substring(content.indexOf("mac_url='"),content.length)
        content = content.substring(9,content.length-3)
        let content_array = content.split('$$$')
        let line_array = []
        for(let i=0; i<content_array.length; ){
            let item = content_array[i].split('#')
            let obj_array = []
            for(let j=0;j<item.length;j++){
                let item_array = item[j].split('$')
                obj_array.push({
                    title: item_array[0],
                    url: item_array[1]
                })
            }
            line_array.push({
                id: i,
                title: '线路' + ++i,
                ova: obj_array
            })
        }
        return line_array
    }
    return []
}

module.exports.hot_play_list = hot_play_list
async function hot_play_list(count_num) {
    let sql = 'SELECT * FROM movie ORDER BY score DESC,scorenum DESC LIMIT '+count_num+',10'
    let movie_list = await db_movie.query(sql)
    if (movie_list instanceof Array && movie_list.length > 0) {
        return movie_list
    }
    return []
}

async function renew_hot_play_list(movie) {
    let actor = db_movie.escape(movie.actor)
    let detail = db_movie.escape(movie.detail)
    let director = db_movie.escape(movie.director)
    let images = db_movie.escape(movie.images)
    let language = db_movie.escape(movie.language)
    let location = db_movie.escape(movie.location)
    let title = db_movie.escape(movie.title)
    let sql = 'insert into movie(id,actor,detail,director,images,language,location,ova,score,scorenum,status,title,year) values('+movie.id+','+actor+','+detail+','+director+','+images+','+language+','+location+','+movie.ova+','+movie.score+','+movie.scorenum+',"'+movie.status+'",'+title+',"'+movie.year+'")' +
        ' ON DUPLICATE KEY UPDATE ova='+movie.ova+',score='+movie.score+',scorenum='+movie.scorenum+',status="'+movie.status+'"'
    db_movie.queryNum(sql)
}